package com.lsh.ofc.proxy.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lsh.base.common.exception.BusinessException;
import com.lsh.base.common.model.CommonResult;
import com.lsh.ofc.proxy.model.*;
import com.lsh.ofc.proxy.util.HttpClientUtils;
import org.apache.http.Consts;
import org.apache.http.Header;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicHeader;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Project Name: SCServiceProxy
 * 北京链商电子商务有限公司
 *
 * @author peter
 * Date: 19/4/20
 * Package Name: com.lsh.ofc.proxy.service
 * Description: SortingCenterServiceProxy
 */
@Component
public class ScServiceProxy {
    private final Logger logger = Logger.getLogger(ScServiceProxy.class);

    private static final String URI_CREATE_CLOUD_SO_URL = "/API/V1/openApi/saveSortingObd";
    private static final String URI_CREATE_CLOUD_PACKAGE_URL = "/API/V1/openApi/saveCloudPackage";
    private static final String URI_CANCEL_CLOUD_ORDER_URL = "/API/V1/openApi/cancelSortingObd";
    private static final String URI_SEND_SC_IBD_URL = "/API/V1/openApi/saveSortingIbd";


    @Value("${sc.server.proxy.path}")
    private String scServerProxyPath;

    @Autowired
    private BaseGoodsServiceProxy baseGoodsServiceProxy;

    /**
     * 云仓订单取消
     *
     * @param soBillCode
     * @param orderType
     * @return
     */
    public boolean cancelCloudOrder(String soBillCode, String warehouseCode, Integer orderType) {
        String uri = this.scServerProxyPath + URI_CANCEL_CLOUD_ORDER_URL;

        JSONObject param = new JSONObject();
        param.put("orderOtherId", soBillCode);
        param.put("orderType", orderType);
        param.put("sourceSystem", "2");
        param.put("warehouseCode", warehouseCode);

        String content = param.toJSONString();
        StringEntity entity = new StringEntity(content, Consts.UTF_8);
        entity.setContentType(ContentType.APPLICATION_JSON.toString());

        logger.info("[POST][URI= " + uri + " ][request:" + content + "]");
        CommonResult<String> result = HttpClientUtils.post(uri, entity, this.buildHeaders(warehouseCode));
        logger.info("[POST][URI= " + uri + " ][response:" + JSON.toJSONString(result) + "]");

        if (!CommonResult.SUCCESS.equals(result.getCode())) {
            throw new BusinessException(CommonResult.ERROR, result.getMessage());
        }

        String data = result.getData();
        JSONObject json = JSONObject.parseObject(data);
        JSONObject head = JSONObject.parseObject(json.getString("head"));
        int status = head.getInteger("status").intValue();
        if (status == 1) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 云仓订单，obd的包裹信息，下发WMS
     *
     * @param reqHead
     * @return
     */
    public boolean pushCloudPackageInfo(CreateWmsCloudPackageReqHead reqHead) {
        String uri = this.scServerProxyPath + URI_CREATE_CLOUD_PACKAGE_URL;
        String content = JSON.toJSONString(reqHead);

        StringEntity entity = new StringEntity(content, Consts.UTF_8);
        entity.setContentType(ContentType.APPLICATION_JSON.toString());

        logger.info("[POST][URI= " + uri + " ][request:" + content + "]");
        CommonResult<String> result = HttpClientUtils.post(uri, entity, this.buildHeaders(reqHead.getWarehouseCode()));
        logger.info("[POST][URI= " + uri + " ][response:" + JSON.toJSONString(result) + "]");

        if (!CommonResult.SUCCESS.equals(result.getCode())) {
            throw new BusinessException(CommonResult.ERROR, result.getMessage());
        }

        String data = result.getData();
        JSONObject json = JSONObject.parseObject(data);
        JSONObject head = JSONObject.parseObject(json.getString("head"));
        int status = head.getInteger("status").intValue();
        if (status == 1) {
            return true;
        } else {
            return false;
        }
    }


    /**
     * 汇总订单生成ibd
     *
     * @param createWgStoReqHead
     * @return
     */
    public void sendIbd(CreateWgStoReqHead createWgStoReqHead) {
        String uri = this.scServerProxyPath + URI_SEND_SC_IBD_URL;

        CreateWmsIbdReqHead reqHead = new CreateWmsIbdReqHead();
        reqHead.setOrderOtherId(createWgStoReqHead.getOrderId());
        reqHead.setWarehouseCode(createWgStoReqHead.getSendWarehouseCode());
        reqHead.setOwnerId(createWgStoReqHead.getOwnerId());
        reqHead.setSupplierName(createWgStoReqHead.getSendWarehouseCode() + "-本地");

        List<CreateWmsIbdReqDetail> details = new ArrayList<>();

        //获取箱规信息
        List<Long> itemCodes = new ArrayList<>();
        for(CreateWgStoReqDetail createWgStoReqDetail:createWgStoReqHead.getItems()){
            itemCodes.add(createWgStoReqDetail.getSkuCode());
        }
        Map<Long,BaseGoods> goodsMap = baseGoodsServiceProxy.getGoodsInfoMapByGoodsCodes(itemCodes,createWgStoReqHead.getMisVenderId());

        for(CreateWgStoReqDetail createWgStoReqDetail:createWgStoReqHead.getItems()){

            //获取箱规，如果不能整除，则按ea出
            BaseGoods baseGoods = goodsMap.get(createWgStoReqDetail.getSkuCode());

            BigDecimal unitQty = createWgStoReqDetail.getQty();

            BigDecimal orderQty;
            String packName;
            BigDecimal packUnit;

            BigDecimal [] result = unitQty.divideAndRemainder(baseGoods.getPackUnit());

            if(result[1].compareTo(BigDecimal.ZERO)==0){
                //能整除
                orderQty = result[0];
                packName = baseGoods.getPackName();
                packUnit = baseGoods.getPackUnit();

            }else {
                orderQty = createWgStoReqDetail.getQty();
                packName = baseGoods.getUnit();
                packUnit = BigDecimal.ONE;
            }
            CreateWmsIbdReqDetail createWmsIbdReqDetail = new CreateWmsIbdReqDetail();
            createWmsIbdReqDetail.setDetailOtherId(createWgStoReqDetail.getLineNo());
            createWmsIbdReqDetail.setOrderQty(orderQty);
            createWmsIbdReqDetail.setUnitQty(unitQty);
            createWmsIbdReqDetail.setSkuCode(createWgStoReqDetail.getGoodsId());
            createWmsIbdReqDetail.setUnitName(baseGoods.getUnit());
            createWmsIbdReqDetail.setPackUnit(packUnit);
            createWmsIbdReqDetail.setOriQty(unitQty);
            createWmsIbdReqDetail.setPackName(packName);
            details.add(createWmsIbdReqDetail);
        }
        reqHead.setDetails(details);
        String content = JSON.toJSONString(reqHead);
        StringEntity entity = new StringEntity(content, Consts.UTF_8);
        entity.setContentType(ContentType.APPLICATION_JSON.toString());

        logger.info("[POST][URI= " + uri + " ][request:" + content + "]");
        CommonResult<String> result = HttpClientUtils.post(uri, entity, this.buildHeaders(reqHead.getWarehouseCode()));
        logger.info("[POST][URI= " + uri + " ][response:" + JSON.toJSONString(result) + "]");

        if (!CommonResult.SUCCESS.equals(result.getCode())) {
            throw new BusinessException(CommonResult.ERROR, result.getMessage());
        }

        String data = result.getData();
        JSONObject json = JSONObject.parseObject(data);
        JSONObject head = JSONObject.parseObject(json.getString("head"));

        int status = head.getInteger("status").intValue();
        if (status != 1) {
            throw new BusinessException(CommonResult.ERROR,head.getString("message"));
        }
    }

    /**
     * 云仓订单so信息，下发sc分拣中心
     *
     * @param scSoReqHead
     * @return
     */
    public boolean pushCloudSo(CreateScSoReqHead scSoReqHead) {
        String uri = this.scServerProxyPath + URI_CREATE_CLOUD_SO_URL;
        String content = JSON.toJSONString(scSoReqHead);

        StringEntity entity = new StringEntity(content, Consts.UTF_8);
        entity.setContentType(ContentType.APPLICATION_JSON.toString());

        logger.info("[POST][URI= " + uri + " ][request:" + content + "]");
        CommonResult<String> result = HttpClientUtils.post(uri, entity, this.buildHeaders(scSoReqHead.getWarehouseCode()));
        logger.info("[POST][URI= " + uri + " ][response:" + JSON.toJSONString(result) + "]");

        if (!CommonResult.SUCCESS.equals(result.getCode())) {
            throw new BusinessException(CommonResult.ERROR, result.getMessage());
        }

        String data = result.getData();
        JSONObject json = JSONObject.parseObject(data);
        JSONObject head = JSONObject.parseObject(json.getString("head"));
        int status = head.getInteger("status").intValue();
        if (status == 1) {
            return true;
        } else {
            return false;
        }
    }


    private Header[] buildHeaders(String warehouseCode) {
        Header[] headers = {new BasicHeader("warehouseCode", warehouseCode)};
        return headers;
    }

}
